package com.ganee.agora.view

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RelativeLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.ganee.agora.R
import com.ganee.agora.adapter.CommentAdapter
import com.ganee.agora.event.CommentEvent
import com.ganee.agora.model.CommentEntity
import com.ganee.agora.viewmodel.TidbitsViewModel
import com.ganee.agora.widget.dialog.BottomDialog
import com.ganee.agora.widget.ratingbar.AndRatingBar
import com.ganee.baselib.arouter.Constance
import com.ganee.baselib.mvvmlibrary.base.BaseActivity
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_comment.*
import kotlinx.android.synthetic.main.toolbar_with_title.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import org.json.JSONException
import org.json.JSONObject
import java.lang.ref.WeakReference

//评论 Tidbits
@Route(path = Constance.ACTIVITY_URL_COMMENT)
class CommentActivity : BaseActivity<TidbitsViewModel>(), View.OnClickListener {

    @JvmField
    @Autowired(name = "activeId")
    var activeId: String? = null

    private var mAdapter: CommentAdapter? = null
    private val mList:MutableList<CommentEntity> = mutableListOf()

    private val emptyView: View
        get() {
            val view = LayoutInflater.from(this).inflate(R.layout.common_empty_data, tidbitsRecyclerView.parent as ViewGroup, false)
            return view
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_comment)
        ARouter.getInstance().inject(this)
        initView()
        initAdapter()
        initRequestData()
    }

    private fun initRequestData() {
        val requestData = JSONObject()
        try {
            requestData.put("activeId", activeId)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString())
        viewModel.getCommentList(requestBody)

        viewModel.commentList.observe(this, Observer<List<CommentEntity>> {
            mList.clear()
            mList.addAll(it)
            mAdapter!!.notifyDataSetChanged()
        })
    }

    private fun initAdapter() {
        tidbitsRecyclerView.setHasFixedSize(true)
        tidbitsRecyclerView.layoutManager = LinearLayoutManager(this)

        mAdapter = CommentAdapter(mList)
        tidbitsRecyclerView.addOnItemTouchListener(object : OnItemClickListener() {

            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

            }

        })
        mAdapter!!.emptyView = emptyView
        tidbitsRecyclerView.adapter = mAdapter
    }

    private fun initView() {
        toolbarCancel.setOnClickListener(this)
        toolbarTitle.text = "Tidbits"
        comment_rl.setOnClickListener(this)
        comment_arb_score.rating = 0f

    }

    override fun getViewModel(): TidbitsViewModel {
        return ViewModelProviders.of(this@CommentActivity).get(TidbitsViewModel::class.java)
    }

    override fun onClick(v: View?) {
        when(v!!.id){
            R.id.toolbarCancel -> {
                finish()
            }
            R.id.comment_rl -> {
                initCommentDialog()
            }
        }
    }

    //评论对话框
    private fun initCommentDialog() {
        val view = View.inflate(this@CommentActivity, R.layout.dialog_tidbits_rating, null)
        val ratingScore = view.findViewById<AndRatingBar>(R.id.dialog_tidbits_arb_score) as AndRatingBar
        val etTitle = view.findViewById<EditText>(R.id.dialog_tidbits_et_title) as EditText
        val tvContent = view.findViewById<EditText>(R.id.dialog_tidbits_et_content) as EditText
        val rlComment = view.findViewById<RelativeLayout>(R.id.dialog_tidbits_rl) as RelativeLayout

        var dialog:BottomDialog? = null
        val weakReference = WeakReference<Activity>(this@CommentActivity)
        if (weakReference.get() != null) {
            dialog = BottomDialog(weakReference.get(), view, false, true)
            dialog!!.show()
        }

        rlComment.setOnClickListener{
            dialog!!.dismiss()
            val score = ratingScore.rating.toString()
            val commentText = tvContent.text.toString()
            val requestData = JSONObject()
            try {
                requestData.put("activeId", activeId)
                requestData.put("score", score)
                requestData.put("commentText", commentText)
            } catch (e: JSONException) {
                e.printStackTrace()
            }
            val requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString())
            viewModel.postComment(requestBody)
            viewModel.commentValue.observe(this, Observer<CommentEntity> {
                mList.add(it)
                mAdapter!!.notifyDataSetChanged()
                EventBus.getDefault().post(CommentEvent("comment"))
            })
        }
    }
}
